package me.yidasanqian.crowdfunding.service.impl;

import me.yidasanqian.crowdfunding.domain.Address;
import me.yidasanqian.crowdfunding.mapper.AddressMapper;
import me.yidasanqian.crowdfunding.service.IAddressService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Linyu Chen
 */
@Service
@Transactional
public class AddressService implements IAddressService {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private AddressMapper addressMapper;

    @Override
    public void save(Address address) {
        addressMapper.insert(address);
    }

    @Override
    @CacheEvict(value = "CONSTANT", key = "'address_'+#addressId")
    public void deleteById(Long addressId) {
        addressMapper.deleteByPrimaryKey(addressId);
    }

    @Override
    @CachePut(value = "CONSTANT", key = "'address_'+#address.id")
    public void update(Address address) {
        addressMapper.updateByPrimaryKey(address);
    }

    @CachePut(value = "CONSTANT", key = "'addressList_userId'+#userId")
    public List<Address> listAddress(Long userId) {
        return addressMapper.listAddress(userId);
    }

    @Override
    @Cacheable(value = "CONSTANT", key = "'address_'+#addressId")
    public Address getAddress(Long addressId) {
        return addressMapper.selectByPrimaryKey(addressId);
    }

    @Override
    public int countAddress(Long userId) {
        return addressMapper.count(userId);
    }

    @Cacheable(value = "CONSTANT", key = "'address_'+#addressId")
    public Address getAddressFromCache(Long addressId) {
        log.info("从数据库中进行获取的 id ==>" + addressId);
        return addressMapper.selectByPrimaryKey(addressId);
    }

    @CacheEvict(value = "CONSTANT", key = "'address_'+#addressId")
    public void deleteFromCache(Long addressId) {
        log.info("从缓存中删除的 id ==>" + addressId);
    }
}
